package com.wangcang.widgetlibrary.activity;

import android.Manifest;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.wangcang.widgetlibrary.R;
import com.wangcang.widgetlibrary.activity.base.BaseActivity;
import com.wangcang.widgetlibrary.bubble.PopUpUtils;
import com.wangcang.widgetlibrary.media.DirectoryAdapter;
import com.wangcang.widgetlibrary.media.ImageFolder;
import com.wangcang.widgetlibrary.media.OnItemSelectListener;
import com.wangcang.widgetlibrary.media.SelectAdapter;
import com.wangcang.widgetlibrary.popupwindow.EasyPopupWindow;
import com.wangcang.widgetlibrary.tools.PermissionUtils;
import com.wangcang.widgetlibrary.tools.ThreadUtils;
import com.wangcang.widgetlibrary.tools.ToastUtils;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SelectImageActivity extends BaseActivity implements PermissionUtils.PermissionCallbacks, View.OnClickListener, EasyPopupWindow.ChildClickListener {
    private TextView mTopSwitch;
    private TextView mTopCancel;

    private GridView mGridView;
    private SelectAdapter mSelectAdapter;

    private EasyPopupWindow mEasyPopupWindow;

    private List<String> mImagePathList;
    private List<ImageFolder> mImageFolderList;

    private static final int MSG_SCAN_SUCCEED = 0x110;

    public static final String SELECT_IMAGE_PATH = "select_image_path";

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SCAN_SUCCEED:
                    dismissProgress();

                    if (mImagePathList.size() == 0) {
                        ToastUtils.showToast(R.string.scan_no_photo);
                        return;
                    }

                    mSelectAdapter = new SelectAdapter(SelectImageActivity.this, mImagePathList);
                    mGridView.setAdapter(mSelectAdapter);

                    mSelectAdapter.setOnItemSelectListener(new OnItemSelectListener() {
                        @Override
                        public void onItemSelect(String path) {
                            //选择图片
                            Intent intent = new Intent();
                            intent.putExtra(SELECT_IMAGE_PATH, path);
                            setResult(RESULT_OK, intent);
                            finishActivity();
                        }
                    });
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_image);

        initView();
        initEvent();
    }

    private void initView() {
        mTopSwitch = findView(R.id.top_switch);
        mTopCancel = findView(R.id.top_cancel);

        mGridView = findView(R.id.grid_view);

        mImagePathList = new ArrayList<>();
        mImageFolderList = new ArrayList<>();

        PermissionUtils.requestPermissions(this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE }, 1);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> permissionList) {
        //当requestCode相同时候，permissions.size == 请求的权限数时候，认为权限请求成功
        if(requestCode == 1 && permissionList.size() == 1) {
            initData();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> permissionList) {
        //调用了一次拒绝权限认为失败
        if(requestCode == 1){
            ToastUtils.showToast("拒绝了权限" + permissionList.get(0));
            PermissionUtils.permissionDialog(this, permissionList, null);
        }
    }

    /**
     * 利用ContentProvider扫描手机中的所有图片
     */
    private void initData() {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            ToastUtils.showToast(R.string.external_storage_is_disable);
            return;
        }

        showProgressDialog(getResources().getString(R.string.loading));

        ThreadUtils.newThread(new Runnable() {
            @Override
            public void run() {
                Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                Cursor cursor = getContentResolver().query(uri, null, MediaStore.Images.Media.MIME_TYPE + "= ? or " + MediaStore.Images.Media.MIME_TYPE + "= ? or " + MediaStore.Images.Media.MIME_TYPE + "= ?", new String[]{ "image/jpg", "image/jpeg", "image/png" }, MediaStore.Images.Media.DATE_MODIFIED);

                Set<String> directorySet = new HashSet<>();

                while(cursor.moveToNext()) {
                    //获取图片的路径
                    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));

                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null) {
                        continue;
                    }

                    String parentPath = parentFile.getAbsolutePath();

                    ImageFolder imageFolder;

                    if (directorySet.contains(parentPath)) {
                        continue;
                    } else {
                        directorySet.add(parentPath);

                        imageFolder = new ImageFolder();
                        imageFolder.setDirectory(parentPath);
                        imageFolder.setFirstImagePath(path);
                    }

                    if (parentFile.list() == null) {
                        continue;
                    } else {
                        File[] listFiles = parentFile.listFiles(new FilenameFilter() {
                            @Override
                            public boolean accept(File dir, String name) {
                                if (name.toLowerCase().endsWith(".jpg") || name.toLowerCase().endsWith(".jpeg") || name.toLowerCase().endsWith(".png")) {
                                    return true;
                                }

                                return false;
                            }
                        });

                        for (int i = listFiles.length - 1; i >= 0; i--) {
                            mImagePathList.add(listFiles[i].getAbsolutePath());
                        }

                        imageFolder.setCount(listFiles.length);
                        mImageFolderList.add(imageFolder);
                    }
                }

                cursor.close();

                mHandler.sendEmptyMessage(MSG_SCAN_SUCCEED);
            }
        });
    }

    private void initEvent() {
        mTopSwitch.setOnClickListener(this);
        mTopCancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.top_switch:
                Drawable drawable = getResources().getDrawable(R.drawable.directory_arrow_up);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                mTopSwitch.setCompoundDrawables(null, null, drawable, null);

                mEasyPopupWindow = PopUpUtils.showPopUpTop(R.layout.upload_directory_popupwindow, this, mTopSwitch, true, this);

                mEasyPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        Drawable drawable = getResources().getDrawable(R.drawable.directory_arrow_down);
                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                        mTopSwitch.setCompoundDrawables(null, null, drawable, null);
                    }
                });
                break;
            case R.id.top_cancel:
                finishActivity();
                break;
            default:
                break;
        }
    }

    @Override
    public void getChildView(int layoutId, View view) {
        ListView listView = (ListView) view.findViewById(R.id.list_view);
        DirectoryAdapter adapter = new DirectoryAdapter(this, R.layout.item_directory, mImageFolderList);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mEasyPopupWindow != null && mEasyPopupWindow.isShowing()) {
                    mEasyPopupWindow.dismiss();
                }

                ImageFolder imageFolder = mImageFolderList.get(position);

                mTopSwitch.setText(imageFolder.getName());

                File parentFile = new File(imageFolder.getFirstImagePath()).getParentFile();

                if (parentFile == null) {
                    return;
                }

                File[] listFiles = parentFile.listFiles(new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String name) {
                        if (name.toLowerCase().endsWith(".jpg") || name.toLowerCase().endsWith(".jpeg") || name.toLowerCase().endsWith(".png")) {
                            return true;
                        }

                        return false;
                    }
                });

                mImagePathList.clear();

                for (int i = listFiles.length - 1; i >= 0; i--) {
                    mImagePathList.add(listFiles[i].getAbsolutePath());
                }

                mSelectAdapter.notifyDataSetChanged();
            }
        });
    }
}
